package com.qqt.csr.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.filter.Filter;
import com.alibaba.fastjson2.filter.SimplePropertyPreFilter;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

public class JsonUtil {

    /**
     * 序列化为字符串
     * @param obj
     * @return
     */
    public static  String toJson(Object obj) {
        return JSON.toJSONString(obj);
    }
    /**
     * 序列化为字符串
     *
     * @param obj
     * @return
     */
    public static String toJson(Object obj, List<String> excludePropertyList) {
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
        filter.getExcludes().addAll(excludePropertyList);
        return toJson(obj, filter);
    }
    /**
     * 序列化为字符串
     *
     * @param obj
     * @return
     */
    public static String toJson(Object obj, String... excludeProperty) {
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
        filter.getExcludes().addAll(Lists.newArrayList(excludeProperty));
        return toJson(obj, filter);
    }

    /**
     * 序列化为字符串
     *
     * @param obj
     * @return
     */
    public static String toJson(Object obj, Filter filter) {
        return JSON.toJSONString(obj, filter);
    }

    /**
     * 反序列化为对象
     * @param json
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> T toObject(String json, Class<T> clazz) {
        if(StringUtils.isBlank(json)){
            return null;
        }
        return JSON.parseObject(json, clazz);
    }

    /**
     * 反序列化为集合
     * @param json
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> List<T> toList(String json, Class<T> clazz) {
        if(StringUtils.isBlank(json)){
            return Lists.newArrayList();
        }
        return JSON.parseArray(json, clazz);
    }
}
